<?php
require_once APPPATH.'third_party/kdt/lib/YZGetTokenClient.php';
require_once APPPATH.'third_party/kdt/lib/YZTokenClient.php';
/**
 * Created by PhpStorm.
 * User: luzhaoyang
 * Date: 2017/6/23
 * Time: 11:30
 */
class Kdt_api_model extends Base_Model
{
    private $_appid;
    private $_appsecret;
    private $_client;
    private $_client_id;
    private $_client_secret;
    private $_access_token;
    private $_refresh_token;
    private $_redis;
    private $_expires_in;
    private $_refresh_expires_in;

    public function __construct()
    {
        parent::__construct();

        $this->config->load('kdt');
        $this->_appid = $this->config->item('appid');
        $this->_appsecret = $this->config->item('appsecret');
        $this->_client_id = $this->config->item('clientid');
        $this->_client_secret = $this->config->item('clientSecret');
        $this->_refresh_expires_in = 2160000;
        $this->load->model('redis_model');
        $this->_redis = $this->redis_model->getRedisInstance();
    }

    public function checkToken()
    {
        $token = $this->_redis->get('kdt_access_token');
        //超时重新获取
        if ($token===false){
            $rtoken = $this->_redis->get('kdt_refresh_token');
            //重新授权,跳转页面
            if ($rtoken===false){
                $this->getToken();
            }
            //刷新token
            else{
                $this->_refresh_token=$rtoken;
                $this->refreshToken();
            }
        }else{$this->_access_token=$token;}
    }

    public function getAccessToken()
    {
        return $this->_access_token;
    }

    public function getToken()
    {
        $this->_client = new YZGetTokenClient( $this->_client_id , $this->_client_secret );
        $redirectUrl = 'http://api.nldou.com/salesman/passport/authcallback';
        $this->_client->getCode($redirectUrl);
    }

    public function authcallback()
    {
        $this->_client = new YZGetTokenClient( $this->_client_id , $this->_client_secret );
        $keys = array();
        $redirectUrl = 'http://api.nldou.com/salesman/passport/authcallback';
        $type = 'oauth';
        $keys['code'] = $_GET['code'];
        $keys['redirect_uri'] = $redirectUrl;

        $res = $this->_client->getToken( $type , $keys );
        $this->_access_token=$res['access_token'];
        $this->_refresh_token=$res['refresh_token'];
        $this->_expires_in=(int)$res['expires_in'];
        $this->saveToken();
    }

    public function refreshToken()
    {
        $this->_client = new YZGetTokenClient( $this->_client_id , $this->_client_secret );
        $type = 'refresh_token';
        $keys = array();
        $keys['refresh_token'] = $this->_refresh_token;

        $res = $this->_client->getToken( $type , $keys );
        $this->_access_token=$res['access_token'];
        $this->_refresh_token=$res['refresh_token'];
        $this->_expires_in=(int)$res['expires_in'];
        $this->saveToken();
    }

    public function saveToken()
    {
        //保存access_token,过期时间（7天-1小时）
        $this->_redis->set('kdt_access_token',$this->_access_token);
        $this->_redis->expire('kdt_access_token',$this->_expires_in-3600);
        //保存refresh_token,过期时间（25天）
        $this->_redis->set('kdt_refresh_token',$this->_refresh_token);
        $this->_redis->expire('kdt_refresh_token',$this->_refresh_expires_in);
    }

    public function checkSalesman($mobile,$openid)
    {
        $sm=$this->getSalesmanAccount($mobile);
        if ($sm===false) return false;//不是销售员
//        $user=$this->getUserInfo('',$sm['fans_id']);
        $user=$this->getUserOpenid($mobile);
        if ($user===false) return false;//手机有没有绑定有赞
        elseif ($user['open_id']!==$openid) return false;//登陆的微信不是申请代言人的微信
        else return $sm;
    }

    public function getUserInfo($openid='',$fansid='',$fields='')
    {
        $this->checkToken();
        $this->_client = new YZTokenClient($this->_access_token);

        $method = 'youzan.users.weixin.follower.get';
        $methodVersion = '3.0.1';

        $params = array();
        if (!empty($openid)) $params['weixin_openid']=$openid;
        if (!empty($fansid)) $params['fans_id']=$fansid;
        if (!empty($fansid)) $params['fields']=$fields;

        $files = array();

        $res = $this->_client->post($method, $methodVersion, $params, $files);
        if (isset($res['response']['user'])) return $res['response']['user'];
        else return false;
    }

    public function getBatchUserInfo($openids='',$fansids='',$fields='')
    {
        $this->checkToken();
        $this->_client = new YZTokenClient($this->_access_token);

        $method = 'youzan.users.weixin.follower.gets';
        $methodVersion = '3.0.0';

        $params = array();
        if (!empty($openids)) $params['weixin_openids']=$openids;
        if (!empty($fansids)) $params['fans_ids']=$fansids;
        if (!empty($fields)) $params['fields']=$fields;
//        $params['page_no'] = 1;
//        $params['page_size'] = 40;

        $files = array();

        $res = $this->_client->post($method, $methodVersion, $params, $files);

        if (isset($res['response']['user'])) return $res['response']['user'];
        else return false;
    }

    public function getUserOpenid($mobile)
    {
        $this->checkToken();
        $this->_client = new YZTokenClient($this->_access_token);

        $method = 'youzan.user.weixin.openid.get';
        $methodVersion = '3.0.0';

        $params = array();
        $params['mobile']=$mobile;

        $files = array();

        $res = $this->_client->post($method, $methodVersion, $params, $files);
        if (isset($res['response']['open_id'])) return $res['response'];
        else return false;
    }

    public function getSalesmanAccount($mobile)
    {
        $this->checkToken();
        $this->_client = new YZTokenClient($this->_access_token);

        $method = 'youzan.salesman.account.get';
        $methodVersion = '3.0.0';

        $params = array(
            'mobile' => $mobile,
            'fans_id'=>1,
            'fans_type' => 1
        );
        $files = array();

        $res = $this->_client->post($method, $methodVersion, $params, $files);
        if (isset($res['response']['seller'])) return $res['response'];
        else return false;
    }

    public function getSalesmanAccountScore($mobile,$pageno=1,$pagesize=20)
    {
        $this->checkToken();
        $this->_client = new YZTokenClient($this->_access_token);

        $method = 'youzan.salesman.account.score.search';
        $methodVersion = '3.0.0';

        $params = array(
            'mobile' => $mobile,
            'fans_id'=>0,
            'fans_type' => 1,
            'page_no' => $pageno,
            'page_size' => $pagesize,
            'start_time' => '0',
            'end_time' => '0'
        );
        $files = array();

        $res = $this->_client->post($method, $methodVersion, $params, $files);
        if (isset($res['response'])) return $res['response'];
        else return false;
    }

    public function getSalesmanTrades($mobile,$pageno=1,$pagesize=20)
    {
        $this->checkToken();
        $this->_client = new YZTokenClient($this->_access_token);

        $method = 'youzan.salesman.trades.get';
        $methodVersion = '3.0.0';

        $params = array(
            'mobile' => $mobile,
            'fans_id'=>0,
            'fans_type' => 1,
            'page_no' => $pageno,
            'page_size' => $pagesize,
            'start_time' => '0',
            'end_time' => '0'
        );
        $files = array();

        $res = $this->_client->post($method, $methodVersion, $params, $files);
        if (isset($res['response'])) return $res['response'];
        else return false;
    }
    //获取销售员分销商品信息
    public function getSalesmanItems()
    {
        $this->checkToken();
        $this->_client = new YZTokenClient($this->_access_token);

        $method = 'youzan.salesman.items.get';
        $methodVersion = '3.0.0';

        $itemids = '321125603';/*幼小衔接*/
        $itemids .= ',321296139';/*专注力*/
        $itemids .= ',326133868';/*数学*/
        $itemids .= ',343737481';/*加10赛*/
        $itemids .= ',353577094';/*小鸭农场*/
        $itemids .= ',353165408';/*小兔一家亲*/
        $itemids .= ',353539809';/*表情帝*/
        $itemids .= ',353165957';/*寻找喵喵*/
        $itemids .= ',353485416';/*指环王*/
        $itemids .= ',353164478';/*GOGO碰*/
        $itemids .= ',353575381';/*分类连连看*/
        $itemids .= ',353574841';/*图形接龙*/
        $itemids .= ',353577481';/*快乐奖惩*/

        $params = array(
            'item_ids' => $itemids
        );
        $files = array();

        $res = $this->_client->post($method, $methodVersion, $params, $files);
        echo '<pre>';
        var_dump($res);
        echo '</pre>';
    }

    public function getSalesmanList($pagesize,$pageno)
    {
        $this->checkToken();
        $this->_client = new YZTokenClient($this->_access_token);

        $method = 'youzan.salesman.accounts.get';
        $methodVersion = '3.0.0';

        $params = array(
            'page_size'=>$pagesize,
            'page_no'=>$pageno,
        );

        $files = array();

        return $this->_client->post($method, $methodVersion, $params, $files);
    }

    public function getCouponList()
    {
        $this->checkToken();
        $this->_client = new YZTokenClient($this->_access_token);

        $method = 'youzan.ump.coupons.unfinished.search';
        $methodVersion = '3.0.0';

        $params = array();

        $files = array();

        $res = $this->_client->post($method, $methodVersion, $params, $files);
        if (isset($res['response']['coupons'])) return $res['response']['coupons'];
        else return false;
    }

    public function takeCoupon($couponid,$openid)
    {
        $this->checkToken();
        $this->_client = new YZTokenClient($this->_access_token);

        $method = 'youzan.ump.coupon.take';
        $methodVersion = '3.0.0';

        $params = array(
            'weixin_openid'=>$openid,
            'coupon_group_id'=>$couponid
        );

        $files = array();

        return $this->_client->post($method, $methodVersion, $params, $files);
    }
    public function getSalesmanCustomers($mobile,$pageno=1,$pagesize=20)
    {
        $this->checkToken();
        $this->_client = new YZTokenClient($this->_access_token);

        $method = 'youzan.salesman.customers.get';
        $methodVersion = '3.0.0';

        $params = array(
            "fans_id"=>0,
            "fans_type"=>1,
            "mobile"=>$mobile,
            "page_no"=>$pageno,
            "page_size"=>$pagesize
        );

        $files = array();

        $res = $this->_client->post($method, $methodVersion, $params, $files);
        if (isset($res['response'])) return $res['response'];
        else return false;
    }
    //设置mod_salesman在mod_user中的uid
    public function syncSMUid()
    {
        $this->load->database();
        $offset=0;
        $limit=10;
        while (true){
            $res = $this->db->select('id,phone')->from('mod_salesman')->limit($limit,$offset)->get()->result_array();
            if (empty($res)) break;
            foreach($res as $row){
                $openid = $this->getUserOpenid($row['phone']);
                if ($openid===false) {
                    echo "smid:".$row['id']." kdt api error".PHP_EOL;
                    continue;
                }
                $user = $this->db->select('uid')->from('mod_user')->where('wx_openid=',$openid['open_id'])->get()->row_array();
                if (!empty($user)){
                    if ($this->db->update('mod_salesman',array('uid'=>$user['uid']),array('id'=>$row['id']))){
                        echo "smid:".$row['id']." uid:".$user['uid']." success".PHP_EOL;
                    }else{echo "smid:".$row['id']." uid:".$user['uid']." update fail".PHP_EOL;}
                }
            }
            $offset+=$limit;
        }
    }
}